package com.woniuxy.rms.service.impl;

import com.woniuxy.rms.dao.*;
import com.woniuxy.rms.exception.RoleException;
import com.woniuxy.rms.pojo.*;
import com.woniuxy.rms.service.RoleService;
import com.woniuxy.rms.util.DataResult;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Auther: ChenGang  <br/>
 * Date: 2020/3/24 0024:上午 11:07  <br/>
 * Description:角色服务层
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleService {

    @Autowired
    RolesMapper rolesMapper;

    @Autowired
    RoleMenuMapper roleMenuMapper;

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    PropertyMapper propertyMapper;

    @Autowired
    VendorMapper vendorMapper;

    @Override
    public List<Roles> findAll() {
        return rolesMapper.findAll();
    }

    @Override
    public DataResult insert(Roles roles,String id) {
        //判断角色是否存在
        List<Roles> roles1 = rolesMapper.findByRole(roles.getRole());
        if (roles1.size() > 0){
            return DataResult.failed("角色名已存在！");
        }else {
            //添加角色，并将id赋值给对象
            Admins admin = (Admins) SecurityUtils.getSubject().getPrincipal();
            roles.setAdminId(admin.getId());
            roles.setCreateTime(new Date());
            rolesMapper.save(roles);
        }
        if (id.equals("")){
            throw new RoleException("请为角色分配权限！");
        }
        //截取字符串，得到菜单权限的id集合
        List<Integer> ids = Arrays.stream(id.split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
        //为角色添加权限
        //封装角色菜单中间表数据
        List<RoleMenu> roleMenus = new ArrayList<>();
        for (Integer i : ids) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roles.getId());
            roleMenu.setMenuId(i);
            roleMenus.add(roleMenu);
        }
        //批量添加权限
        roleMenuMapper.saveMenuPerms(roleMenus);
        return DataResult.success();
    }

    @Override
    public DataResult deleteById(Integer id) {
        //先删除角色菜单中间表数据
        roleMenuMapper.deleteByRoleId(id);
        //查询角色信息
        Roles roles = rolesMapper.selectByPrimaryKey(id);
        if (roles.getRole().equals("超级管理员")){
            return DataResult.failed("超级管理员不能删除！");
        }
        rolesMapper.deleteByPrimaryKey(id);
       return DataResult.success();
    }

    @Override
    public DataResult batchDel(String ids) {
        //切割字符串得到id数组
        List<Integer> roleIds = Arrays.stream(ids.split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
        //判断角色是否被分配
        List<Admins> admins = adminMapper.findByRoleIds(roleIds);//管理
        List<Vendor> vendors = vendorMapper.findByRoleIds(roleIds);//商户
        List<Property> properties = propertyMapper.findByRoleIds(roleIds);//物业
        if (admins.size() > 0 || vendors.size() > 0 || properties.size() >0 ){
            return DataResult.failed("角色被分配，不能删除！");
        }
        //删除角色菜单中间表数据
        roleMenuMapper.deleteByRoleIds(roleIds);
        //删除角色数据
        rolesMapper.batchDelByIds(roleIds);
        return DataResult.success();
    }

    @Override
    public DataResult update(Roles roles,String id) {
        //判断角色是否存在
        List<Roles> currentRoles = rolesMapper.findByRole(roles.getRole());
        for (Roles role : currentRoles) {
            if (!role.getId().equals(roles.getId())){
                return DataResult.failed("角色名已存在！");
            }
        }
        roles.setUpdateTime(new Date());
        rolesMapper.updateByPrimaryKeySelective(roles);
        //删除原来的角色菜单
        roleMenuMapper.deleteByRoleId(roles.getId());
        if (id.equals("")){
            throw new RoleException("请为角色分配权限！");
        }
        //截取字符串，得到菜单权限的id集
        List<Integer> ids = Arrays.stream(id.split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
        //为角色添加权限
        //封装角色菜单中间表数据
        List<RoleMenu> roleMenus = new ArrayList<>();
        for (Integer i : ids) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roles.getId());
            roleMenu.setMenuId(i);
            roleMenus.add(roleMenu);
        }
        //批量添加权限
        roleMenuMapper.saveMenuPerms(roleMenus);

       return DataResult.success();
    }

    @Override
    public List<Roles> findByPage(Integer currentPage, Integer pageSize) {
        return rolesMapper.findByPage(currentPage,pageSize);
    }

    @Override
    public Roles findById(Integer roleId) {
        return rolesMapper.selectByPrimaryKey(roleId);
    }
}